package com.smf.lsc.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * 全局过滤器 
 * Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@Configuration
@ConditionalOnProperty(prefix = "security.oauth2", name = "enable", havingValue = "true")
public class AccessGatewayFilter implements GlobalFilter, Ordered {
	
	private final String GATEWAY_ADD_HEAD="smf-gateway";
	private final String GATEWAY_PREMIS_FLAG="PermissionUrl";
	
//  //加强网关身份-资源服务可校验网关身份
//	private static final String GATEWAY_CLIENT_AUTHORIZATION = "Basic " +
//            Base64.getEncoder().encodeToString("gateway-client:123456".getBytes());
	
    @Autowired
    private AuthClient authClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    	
    	//加强网关身份-资源服务可校验网关身份
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
        
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getPath().value();
        //白名单放行
        if (!authClient.hasPermissionControl(url)) {
        	try
        	{
        		//校验token
        		AuthUser authUser=authClient.accessable(request);
	            if (authUser.isFlag()) {
//	            	String GATEWAY_CLIENT_AUTHORIZATION = "Basic " +
////	                      Base64.getEncoder().encodeToString("gateway-client:123456".getBytes());
	            	builder.header(GATEWAY_ADD_HEAD, authUser.getUserInfo());
	                return chain.filter(exchange);
	            }
        	}catch(Exception e)
        	{
        		return unauthorized(exchange,e);
        	}
            
        }
        builder.header(GATEWAY_ADD_HEAD, GATEWAY_PREMIS_FLAG);
        return chain.filter(exchange.mutate().request(builder.build()).build());
        
//        return chain.filter(exchange);
    }

    /**
     * 异常处理，抛出异常信息
     * @param serverWebExchange
     * @param e
     * @return
     */
    private Mono<Void> unauthorized(ServerWebExchange serverWebExchange,Exception e) {
        serverWebExchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer buffer = serverWebExchange.getResponse()
                .bufferFactory().wrap(e.getMessage().getBytes());
        return serverWebExchange.getResponse().writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return 2;
    }
}